/*
 * @Author: TT-hzy 
 * @Date: 2024-06-01 18:23:08
 * @LastEditors: TT-hzy
 * @LastEditTime: 2024-07-26 15:28:51
 * @Description: 
 */

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:hzy_project_template/config/config_index.dart';

class CrystalSnowflakeAnimation extends StatefulWidget {
  const CrystalSnowflakeAnimation({
    super.key,
    this.child,
  });

  final Widget? child;

  @override
  createState() => _CrystalSnowflakeAnimationState();
}

class _CrystalSnowflakeAnimationState extends State<CrystalSnowflakeAnimation> {
  List<CrystalSnowflake> snowflakes = [];
  late Timer timer;

  @override
  void initState() {
    super.initState();
    // 创建晶状体雪花
    for (int i = 0; i < 80; i++) {
      snowflakes.add(CrystalSnowflake(
        x: Random().nextDouble() * 400,
        y: Random().nextDouble() * 800,
        size: Random().nextDouble() * 1 + 0.05,
        drift: Random().nextDouble() * 1 + 1,
        angle: Random().nextDouble() * 4 * pi,
      ));
    }
    // 控制晶状体雪花飘动的定时器
    timer = Timer.periodic(
        const Duration(
          milliseconds: 50,
        ), (timer) {
      for (var snowflake in snowflakes) {
        snowflake.float();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: CrystalSnowflakePainter(snowflakes),
      size: Size.infinite,
      child: widget.child,
    );
  }
}

class CrystalSnowflake {
  double x;
  double y;
  double size;
  double drift;
  double angle;
  CrystalSnowflake({
    required this.x,
    required this.y,
    required this.size,
    required this.angle,
    required this.drift,
  });

  void float() {
    x += drift * cos(angle);
    y += drift * sin(angle);
    if (x < 0 || x > 400 || y < 0 || y > 800) {
      x = Random().nextDouble() * 400;
      y = Random().nextDouble() * 800;
    }
  }
}

class CrystalSnowflakePainter extends CustomPainter {
  List<CrystalSnowflake> snowflakes;

  CrystalSnowflakePainter(this.snowflakes);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()..color = HzyCommonColor().wbgblacktextcolor;

    for (var snowflake in snowflakes) {
      canvas.drawCircle(
          Offset(snowflake.x, snowflake.y), snowflake.size, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
